<?php

namespace app\model;

use think\facade\Db;

class OrderApprovalUserModel extends BaseModel
{
    protected $name = 'dingdan_approval_user';


    public const PENDING = 100; //待开始
    public const APPROVING = 200; //审批中
    public const APPROVED = 300; //通过
    public const REJECTED = 400; //驳回

    /**
     * Notes: 待我审批的 订单
     * User: chenLei
     * Date: 9/14/25
     * @param $params
     * @return mixed
     */
    public function pendingApproval($params)
    {
        $where = [];
        $where[] = ['u.user_id', '=', $params['login_user_id']];
        $where[] = ['u.status', 'in', [self::APPROVING, self::PENDING]]; //查询待开始和该我审批的 状态
        $where[] = ['a.status', '=', OrderApprovalModel::STATUS_ING]; // 审批流程要是等于 正在审批中的
        if (!empty($params['dingdan_code'])) {
            $where[] = ['d.digndan_code', '=', $params['dingdan_code']];
        }
        if (!empty($params['product_name'])) {
            $where[] = ['d.product_name', 'like', '%' . $params['dingdan_code'] . '%'];
        }


        return $this->alias('u')->leftJoin('dingdan_approval a', 'a.id = u.dingdan_approval_id')
            ->leftJoin('dingdan d', 'd.id = a.dingdan_id')
            ->where($where)
            ->order('d.approval_time desc')
            ->field('d.*,a.status as approval_status,u.status as user_status,u.id as approval_user_id')
            ->paginate($params['page_size'] ?? 15)->toArray();


    }


    /**
     * Notes: 我已审批的订单
     * User: chenLei
     * Date: 9/14/25
     * @param $params
     * @return mixed
     */
    public function approved($params)
    {
        $where = [];
        $where[] = ['u.user_id', '=', $params['login_user_id']];
        $where[] = ['u.status', 'in', [self::APPROVED, self::REJECTED]];
        if (!empty($params['dingdan_code'])) {
            $where[] = ['d.digndan_code', '=', $params['dingdan_code']];
        }
        if (!empty($params['product_name'])) {
            $where[] = ['d.product_name', 'like', '%' . $params['dingdan_code'] . '%'];
        }


        return $this->alias('u')->leftJoin('dingdan_approval a', 'a.id = u.dingdan_approval_id')
            ->leftJoin('dingdan d', 'd.id = a.dingdan_id')
            ->where($where)
            ->field('d.*,a.status as approval_status,u.status as user_status,u.id as approval_user_id')
            ->paginate($params['page_size'] ?? 15)->toArray();
    }


    /**
     * Notes: 提交审批
     * User: chenLei
     * Date: 9/14/25
     * @param $params
     * @return false|void
     */
    public function submitApproval($params)
    {
        $info = $this->where('id', $params['approval_user_id'])->findOrEmpty();
        if ($info->isEmpty()) {
            $this->error = '没有查询到该审批节点';
            return false;
        }

        if ($info['status'] != self::APPROVING) {
            $this->error = '该审批节点不是审批中状态';
            return false;
        }

        $orderApprovalModel = new OrderApprovalModel();
        $approval = $orderApprovalModel->where('id', $info->dingdan_approval_id)->findOrEmpty();
        if ($approval->isEmpty() || $approval->status != OrderApprovalModel::STATUS_ING) {
            $this->error = '没有查询到该审批流程';
            return false;
        }

        $orderModel = new OrderModel();
        $order = $orderModel->where('id', $info['dingdan_id'])->findOrEmpty();

        if ($order->isEmpty() || $order->dingdan_status != OrderModel::STATUS_ING) {
            $this->error = '没有查询到该订单或订单状态不是进行中';
            return false;
        }

        Db::startTrans();
        try {

            $date = date('Y-m-d H:i:s');
            $info->status = $params['user_status'];
            $info->op_time = $date;
            $info->save();

            if ($params['user_status'] == self::APPROVED) { //通过
                $logStatus = OrderLogModel::APPROVE;
                $res = $orderApprovalModel->checkAllApprovalsPassed($info->dingdan_approval_id);
                if ($res === false) {
                    throw new \think\Exception($orderApprovalModel->getError());
                }
            } else { //拒绝
                $logStatus = OrderLogModel::REJECT;
                $res = $orderApprovalModel->rejectApprovalProcess($info->dingdan_approval_id);
                if ($res === false) {
                    throw new \think\Exception($orderApprovalModel->getError());
                }
            }


            $orderLog = new OrderLogModel();
            $orderLog->save([
                'dingdan_id' => $info['dingdan_id'],
                'dingdan_approval_id' => $info['dingdan_approval_id'],
                'department_id' => $info['department_id'],
                'user_id' => $params['login_user_id'],
                'remark' => $params['remark'] ?? '',
                'status' => $logStatus,
            ]);


            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();
            $this->error = $exception->getMessage();
            return false;
        }

        return true;
    }


}